package com.meizi.codegenerate.utils;

import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.MemberValuePair;
import com.github.javaparser.ast.expr.NormalAnnotationExpr;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;

import static com.github.javaparser.StaticJavaParser.parseName;

/**
 * @author GG Bond
 * @date 2023/1/12 - 16:05 - 星期四
 * @project lambda
 * @package com.meizi.codegenerate.utils
 * @description 添加注解工具类
 */
public class AnnotationUtils {


    /**
     * 实体类添加注解
     *
     * @param className
     * @param nodeList
     * @param map
     * @param keyS
     * @return
     */
    public static NormalAnnotationExpr setAnnotation(Class className,
                                                     NodeList<MemberValuePair> nodeList,
                                                     Map<String, Object> map, String... keyS) {
        NormalAnnotationExpr annotation = new NormalAnnotationExpr(
                parseName(className.getSimpleName()), nodeList
        );

        Optional.ofNullable(map)
                .ifPresent((pair) -> {
                    for (String key : pair.keySet()) {
                        if (keyS.length == 0) {

                            // 判断value值是否是数字
                            Object value = pair.get(key);
                            if (isNumber(value)) {
                                annotation.addPair(key, "\"" + value + "\"");
                            } else if (checkBoolean(value)) {
                                annotation.addPair(key, value.toString());
                                // 是否是class
                            }else if (isClass(value)){
                                String str = new String((byte[]) value, StandardCharsets.UTF_8);
                                annotation.addPair(key, str + ".class");
                            } else {
                                annotation.addPair(key, "\"" + value + "\"");
                            }
                        }
                    }
                });

        return annotation;
    }

    private static boolean isClass(Object value) {
        if (value instanceof byte[]) {
            return true;
        }
        return false;
    }

    /**
     * 判断value值是否是boolean值
     * @param value
     * @return
     */
    private static boolean checkBoolean(Object value) {
        return value.equals("true") || value.equals("false");
    }

    /**
     * 判断是否为数字可以使用工具类 StringUtils
     * 通过方法 isNumeric 进行判断是否为数字
     * @param str
     * @return
     */
    private static boolean isNumber(Object str) {
        return StringUtils.isNumeric(str.toString());
    }
}
